
//
//  Request.swift
//  ProjectApp
//
//  Created by 邹琳 on 2019/7/24.
//  Copyright © 2019 邹琳. All rights reserved.
//

import Foundation

private let host = URL(string: "https://www.baidu.com")!

struct ResponseResult<T: Decodable>: Decodable {
    let code: Int
    let data: T?
    let message: String
}

struct EmptyResult: Decodable {
    
}

class RequestManager {
    private static let manager = RequestManager()
    private init() {}
    
    /** 测试 */
    static func test(completionHandler: @escaping (_ response: Result<EmptyResult, NSError>) -> Void) {
        let parameters: [String: Any] = ["size": 16, "name": "Bob"]
        let resource = Resource(method: .post, path: "test", params: parameters, hostURL: host)
        
        return manager.request(resource: resource, completionHandler: completionHandler)
    }
}

extension RequestManager: Repository {
    
    var baseURL: URL {
        return host
    }
    
    var commonParams: [String : Any] {
        return [:]
    }
    
    func decode<T>(data: Data) throws -> T where T : Decodable {
        let decoder = JSONDecoder()
        let result = try decoder.decode(ResponseResult<T>.self, from: data)
        if result.code == 0 {
            if T.self == EmptyResult.self {
             	return EmptyResult() as! T
            } else {
                return result.data!
            }
        } else {
            throw NSError.backend(reason: result.message, code: result.code)
        }
    }
}
